//
//  ARVideoFlowViewController.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/2.
//

import UIKit
import JKSwiftExtension

class ARVideoFlowViewController: ARBaseViewController {

    // MARK: - Property
    
    private static let tableViewHeight: CGFloat = {
        return ARHelper.screenHeight() - ARHelper.navigationHeight() - ARHelper.tabBarHeight()
//        return ARHelper.screenHeight()
    }()
    
    private static let cellReuseId = "ar.videoflow.cellreuseid"
    
    private let viewModel = ARVideoFlowViewModel()
    
    private var isCurPlayerPause = false
    @objc dynamic private var currentIndex: Int = 0
    private var hasAddKvo = false
    
    // MARK: - LifeCycle
    
    override func viewDidLoad() {
        super.viewDidLoad()

        viewModel.reloadCommentCallback = { [weak self] index, videoWork in
            
            guard let self = self else {
                return
            }
            
            for cell in self.tableView.visibleCells {
                guard let cell = cell as? ARVideoFlowCell else {
                    continue
                }
                
                if cell.model != videoWork {
                    continue
                }
                cell.model = videoWork
            }
        }
        
        registerNotification()
        
        setupUI()
        loadData()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        // 暂停
        if viewModel.dataSource.isEmpty == false {
            applicationEnterBackground()
        }
        if hasAddKvo {
            self.removeObserver(self, forKeyPath: "currentIndex")
            hasAddKvo = false
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // 播放
        if viewModel.dataSource.isEmpty == false {
            applicationBecomeActive()
        }
        if !hasAddKvo {
            self.addObserver(self, forKeyPath: "currentIndex", options: [.initial, .new], context: nil)
            hasAddKvo = true
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
        
        AVPlayerManager.share().removeAllPlayers()
    }
    
    // MARK: - UI
    
    private func setupUI() {
        
        self.view.layer.masksToBounds = true
        
        self.navigationItem.title = ARHelper.localString("Video")
        if let navigationBar = self.navigationController?.navigationBar {
            navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: ARHelper.font(18, weight: .bold)]
        }
        
        self.ar_setupNavBgImg()
        let rightBarItem = UIBarButtonItem(customView: moreBtn)
        self.navigationItem.rightBarButtonItem = rightBarItem
        
        self.view.addSubview(self.tableView)
        self.tableView.frame = CGRectMake(0, -Self.tableViewHeight, ARHelper.screenWidth(), Self.tableViewHeight * 3)
        self.tableView.contentInset = .init(top: Self.tableViewHeight, left: 0, bottom: Self.tableViewHeight, right: 0)
    }
    
    // MARK: - Netowrk
    
    private func loadData() {
        self.ar.showLoading()
        viewModel.fetchVideoList { [weak self] err in
            self?.ar.hideHUD()
            if let err = err {
                // 直接弹个窗
                let okAction = UIAlertAction(title: ARHelper.localString("Got it"), style: .default) { action in
                    self?.loadData()
                }
                
                let alert = UIAlertController(title: ARHelper.localString("Failed to load"), message: err.localizedDescription)
                alert.addAction(okAction)
                self?.present(alert, animated: true)
                return
            }
            
            self?.tableView.reloadData()
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
//                self?.tableView.jk.scrollToTop(animated: false)
//                self?.tableView.setContentOffset(.init(x: 0, y: -Self.tableViewHeight), animated: true)
                self?.tableView.contentOffset(.init(x: 0, y: -Self.tableViewHeight))
                self?.currentIndex = 0 // 刷新一遍
            }
        }
    }
    
    // MARK: - Action

    @objc private func moreBtnClicked(_ sender: UIButton) {
        // 获取当前作品
        if currentIndex >= viewModel.dataSource.count {
            return
        }
        let work = viewModel.dataSource[currentIndex]
        guard let author = work.author else {
            return
        }
        
        // 判断是否是的作品
        if ARUserManager.shared.userId ?? "" == work.authorId ?? "" {
            return
        }
        
        ARUserRelationshipHelper.workMoreAction(user: author, vc: self) { [weak self] operation, err in
            guard let self = self else {
                return
            }
            if let err = err {
                self.ar.makeToast(err.localizedDescription)
                return
            }
            
            switch operation {
            case .blackList: break
                // 重新加载
//                self.loadData()
                // 通过通知刷新
            case .follow:
                // 更新当前的cell
                // 直接获取当前cell
                for cell in self.tableView.visibleCells {
                    guard let videoCell = cell as? ARVideoFlowCell else {
                        continue
                    }
                    if videoCell.model == work {
                        videoCell.model = videoCell.model
                    }
                }
            }
        }
    }
    
    @objc private func onBlackListChangeNotificationHandler(_ noti: Notification) {
        // 直接刷新
        self.loadData()
    }
    
    // MARK: - KVO
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath != "currentIndex" {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
            return
        }
        
        //设置用于标记当前视频是否播放的BOOL值为NO
        isCurPlayerPause = false
        //获取当前显示的cell
        if let cell = tableView.cellForRow(at: .init(row: currentIndex, section: 0)) as? ARVideoFlowCell {
            cell.startDownloadHighPriorityTask()
            if cell.isPlayerReady {
                cell.replay()
            } else {
                AVPlayerManager.share().pauseAll()
                cell.onPlayerReady = { [weak self, weak cell] in
                    guard let self = self , let cell = cell else {
                        return
                    }
                    if let indexPath = self.tableView.indexPath(for: cell),
                           indexPath.row == self.currentIndex,
                           self.isCurPlayerPause == false
                    {
                        cell.play()
                    }
                    
                }
            }
        }
        
        if currentIndex < viewModel.dataSource.count {
            let work = viewModel.dataSource[currentIndex]
            // 判断是否是的作品
            if ARUserManager.shared.userId ?? "" == work.authorId ?? "" {
                moreBtn.isHidden = true
            } else {
                moreBtn.isHidden = false
            }
        }
    }
    
    // MARK: - Notification
    
    private func registerNotification() {
//        NotificationCenter.default.addObserver(self, selector: #selector(applicationBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(applicationEnterBackground), name: UIApplication.willResignActiveNotification, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(onBlackListChangeNotificationHandler(_:)), name: .blackListChange, object: nil)
    }
    
    @objc private func applicationBecomeActive() {
        // 判断是否正在展示
        if self.view.window == nil || !self.isViewLoaded {
            return
        }
        if let cell = tableView.cellForRow(at: .init(row: currentIndex, section: 0)) as? ARVideoFlowCell {
            if !isCurPlayerPause {
                cell.play()
            }
        }
    }
    
    @objc private func applicationEnterBackground() {
        if let cell = tableView.cellForRow(at: .init(row: currentIndex, section: 0)) as? ARVideoFlowCell {
            isCurPlayerPause = cell.playerView.rate() <= 0
            cell.pause()
        }
    }
    
    // MARK: - Lazy
    
    private lazy var moreBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(.init(named: "common_more"), for: .normal)
        btn.addTarget(self, action: #selector(moreBtnClicked(_:)), for: .touchUpInside)
        return btn
    }()
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.register(ARVideoFlowCell.self, forCellReuseIdentifier: Self.cellReuseId)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.showsVerticalScrollIndicator = false
        return tableView;
    }()
}

extension ARVideoFlowViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return Self.tableViewHeight
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = self.viewModel.dataSource[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: Self.cellReuseId, for: indexPath) as! ARVideoFlowCell
        cell.delegate = self
        cell.model = model
        cell.startDownloadBackgroundTask()
        return cell
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        DispatchQueue.main.async { [weak self] in
            guard let self = self else {
                return
            }
            
            let translatedPoint = scrollView.panGestureRecognizer.translation(in: scrollView)
            scrollView.panGestureRecognizer.isEnabled = false
            
            if translatedPoint.y < -50 && self.currentIndex < (self.viewModel.dataSource.count - 1) {
                self.currentIndex += 1
            }
            if translatedPoint.y > 50 && self.currentIndex > 0 {
                self.currentIndex -= 1
            }
            
            UIView.animate(withDuration: 0.15, delay: 0.0, options: .curveEaseOut) {
                self.tableView .scrollToRow(at: .init(row: self.currentIndex, section: 0), at: .top, animated: false)
            } completion: { flag in
                scrollView.panGestureRecognizer.isEnabled = true
            }
        }
    }
    
}

extension ARVideoFlowViewController: ARVideoFlowCellDelegate {
    
    func videoFlowCellDidClickGiftBtn(_ cell: ARVideoFlowCell!) {
        guard let userId = cell.model.authorId else {
            return
        }
        
        // 暂停
        if viewModel.dataSource.isEmpty == false {
            applicationEnterBackground()
        }
        ARHelper.window().ar.topViewController()?.present(ARSendGiftController(purchseFor: userId), animated: true)
    }
    
    func videoFlowCellDidClickLikeBtn(_ cell: ARVideoFlowCell!) {
        guard let videoWork = cell.model else {
            return
        }
        self.ar.showLoading()
        self.viewModel.likeOrUnlikeVideoWork(videoWork){ [weak self] err in
            self?.ar.hideHUD()
            if let err = err {
                self?.ar.makeToast(err.localizedDescription)
                return
            }
            
            // 刷新一下
            cell.model = cell.model
        }
    }
    
    func videoFlowCellDidClickFollowBtn(_ cell: ARVideoFlowCell!) {
        guard let userId = cell.model.authorId else {
            return
        }
        self.ar.showLoading()
        self.viewModel.followUser(userId) { [weak self] err in
            self?.ar.hideHUD()
            if let err = err {
                self?.ar.makeToast(err.localizedDescription)
                return
            }
            
            // 刷新一下
            self?.ar.makeToast(ARHelper.localString("Follow Successfully"))
            cell.model = cell.model
        }
    }
    
    func videoFlowCellDidClickCommentBtn(_ cell: ARVideoFlowCell!) {
        
        ARKeyboardInputController.showKeyboardInput(at: self) { [weak self] str in
            if str.isEmpty {
                return
            }
            
            self?.ar.showLoading()
            self?.viewModel.postTextComment(str, videoWork: cell.model, completion: { err in
                self?.ar.hideHUD()
                if let err = err {
                    self?.ar.makeToast(err.localizedDescription)
                    return
                }
                
                // 刷新一下
                cell.model = cell.model
            })
        }
    }
    
}
 
